package com.fate.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fate.framework.exception.KKException;
import com.fate.framework.utils.CommonUtil;
import com.fate.framework.utils.SystemUtil;
import com.fate.system.constant.RoleConst;
import com.fate.system.dto.role.RolePageDTO;
import com.fate.system.entity.Role;
import com.fate.system.mapper.RoleMapper;
import com.fate.system.mapper.UserMapper;
import com.fate.system.service.IRoleService;
import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * @author 47349
 * @description 针对表【sys_role(角色表)】的数据库操作Service实现
 * @createDate 2024-08-09 02:02:42
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

  @Resource private UserMapper userMapper;

  public Page<Role> getPageList(RolePageDTO pageDTO) {
    Page<Role> page = SystemUtil.buildPageFromDTO(pageDTO, Role.class);
    return this.lambdaQuery().orderByDesc(Role::getGmtCreate).page(page);
  }

  @Override
  public List<String> getRoleSignsByIds(List<String> roleIds) {
    List<Role> roles = this.listByIds(roleIds);
    if (CommonUtil.isNullOrEmpty(roles)) {
      return List.of();
    }
    return roles.stream().map(Role::getRoleSign).toList();
  }

  @Override
  public String getRoleIdBySign(String sign) {
    Role role = this.lambdaQuery().eq(Role::getRoleSign, sign).one();
    if (CommonUtil.isNullOrEmpty(role)) {
      return null;
    }
    return role.getId();
  }

  @Override
  public List<String> getRoleNameByIds(List<String> roleIds) {
    if (CommonUtil.notNullOrEmpty(roleIds)) {
      List<Role> roles = this.listByIds(roleIds);
      if (CommonUtil.notNullOrEmpty(roles)) {
        return roles.stream().map(Role::getRoleName).toList();
      }
    }
    return List.of();
  }

  @Override
  public Map<String, String> roleId2RoleNameMap(List<String> roleIds) {
    if (CommonUtil.isNullOrEmpty(roleIds)) {
      return Map.of();
    }
    List<Role> roles = this.listByIds(roleIds);
    if (CommonUtil.isNullOrEmpty(roles)) {
      return Map.of();
    }
    return roles.stream().collect(Collectors.toMap(Role::getId, Role::getRoleName));
  }

  @Override
  public void removeRole(String id) {
    int roleIdReferenced = userMapper.isRoleIdReferenced(id);
    if (roleIdReferenced > 0) {
      throw new KKException("该角色已被用户占用");
    }
    Role role = this.getById(id);
    if (CommonUtil.isNullOrEmpty(role)) {
      throw new KKException("角色不存在");
    }
    String roleSign = role.getRoleSign();
    if (RoleConst.DEFAULT_ROLE.equals(roleSign)) {
      throw new KKException("默认角色不能删除");
    }
    this.removeById(id);
  }
}
